<?php
declare (strict_types = 1);

namespace app\command\company;

use app\common\enum\order\OrderStatus;
use app\common\enum\order\OrderType;
use app\common\enum\order\ReceiveType;
use app\common\model\Dealer;
use app\company\model\CompanyOrder;
use app\company\model\DealerStore;
use app\company\model\Payment as PaymentModel;
use app\company\model\PaymentDetail;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class Payment extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('create')
            ->setDescription('the create command');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            Db::startTrans();
            $dealerStoreModel = new DealerStore();
            $orderModel = new CompanyOrder();
            $paymentModel = new PaymentModel();
            $paymentDetailModel = new PaymentDetail();
            $last_mont_first_date = strtotime(date('Y-m-1',strtotime('last month')));
            $last_mont_end_date = strtotime(date('Y-m-d',strtotime(date('Y-m-1'))));
            $year = date('Y',$last_mont_first_date);
            $month = date('n',$last_mont_first_date);
            // 获取有符合条件订单的门店
            $storeIds = $orderModel
                ->where('pid', '<>',0)
                ->where('order_status', OrderStatus::FINISH)
                ->where('order_type', OrderType::SALES)
                ->where('receive_type', ReceiveType::ZQ)
                ->where('create_time', '>=', $last_mont_first_date)
                ->where('create_time', '<', $last_mont_end_date)
                ->column('store_id');
            if($storeIds){
                $storeIds = array_unique($storeIds);
                foreach ($storeIds as $storeId){
                    $dealers = $dealerStoreModel->field('company_id,dealer_id,store_id')->where('store_id', $storeId)->select();
                    foreach ($dealers as $dealer){
                        $paymentDetail = $orderModel->field('id as company_order_id,delivery_amount as money')
                            ->where('store_id', $storeId)
                            ->where('pid', '<>',0)
                            ->where('order_status', OrderStatus::FINISH)
                            ->where('order_type', OrderType::SALES)
                            ->where('receive_type', ReceiveType::ZQ)
                            ->where('create_time', '>=', $last_mont_first_date)
                            ->where('create_time', '<', $last_mont_end_date)
                            ->where('dealer_id', $dealer['dealer_id'])
                            ->select()->toArray();
                        $total = array_sum(array_column($paymentDetail, 'money'));
                        // 组装账期主表数据
                        $data = [
                            'company_id' => $dealer['company_id'],
                            'dealer_id' => $dealer['dealer_id'],
                            'store_id' => $storeId,
                            'company_order_ids' => implode(',',array_column($paymentDetail,'company_order_id')),
                            'year' => $year,
                            'month' => $month,
                            'money' => $total,
                        ];
                        // 新增主表，子表数据
                        $paymentModel->save($data);
                        $paymentId = $paymentModel->getKey();
                        array_walk($paymentDetail, function (&$item) use ($paymentId) {
                            $item['payment_id'] = $paymentId;
                        });
                        $paymentDetailModel->saveAll($paymentDetail);
                    }
                }
            }
            Db::commit();
            // 指令输出
            $output->writeln('执行成功');
        }catch (\Exception $e){
            Db::rollback();
            $output->writeln('执行失败'.$e->getMessage());
        }
    }
}
